from pathlib import Path

from configs.db_conf import DatabaseConf
from configs.log_conf import log_dir
from loguru import logger
from sqlalchemy import (
    Column,
    PrimaryKeyConstraint,
    String,
    UniqueConstraint,
    create_engine,
)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import FlushError
from sqlalchemy_utils import create_database, database_exists

Base = declarative_base()

config = DatabaseConf()

engine = create_engine(
    url="mysql+pymysql://{}:{}@127.0.0.1:{}/wpa?charset=utf8mb4".format(
        config.username, config.password, config.port
    ),
    future=True,
)

if not database_exists(engine.url):
    create_database(engine.url)


Session: sessionmaker = sessionmaker(bind=engine, future=True)

insertPwd_logger = logger
insertPwd_log_file: Path = Path(log_dir, "insertPwd_{time}.log")

insertPwd_logger.add(
    insertPwd_log_file,
    rotation="100 MB",
    retention="1 week",
    compression="zip",
    format="{time:YYYY-MM-DD at HH:mm:ss} - {level} - {message}",
    filter=lambda x: "[insertPwd]" in x["message"],
    level="INFO",
    enqueue=True,
    encoding="utf-8",
)


class Pwd(Base):
    __tablename__: str = "pwd"

    password: Column = Column(String(64), nullable=False, comment="密码")

    # 约束
    __table_args__: tuple = (
        PrimaryKeyConstraint("password"),
        UniqueConstraint("password"),
    )

    @staticmethod
    def insert(subfile: Path, password: str) -> None:
        """
        description: 添加密码
        return      {*}
        author     : Senkita
        """
        with Session.begin() as session:
            try:
                session.add(Pwd(password=password))
                session.commit()
            except IntegrityError:
                insertPwd_logger.error(
                    "[insertPwd] {}的{}重复了。".format(subfile, password)
                )
            except FlushError:
                insertPwd_logger.error(
                    "[insertPwd] {}的{}录不进去。".format(subfile, password)
                )
            finally:
                session.close()
